#include "stdafx.h"

#include <functional>

#include <QNetworkAccessManager>
#include <QNetworkRequest>
#include <QNetworkReply>

#include "Item.h"

#include "ui_ItemFoundDialog.h"
#include "ItemFoundDialog.h"

QImage loadImageFromUrl(const QString &url);
void loadImageFromUrlAsync(const QString &url, std::function<void(QImage &img)> onFinished);

ItemFoundDialog::ItemFoundDialog(const Item &item, QWidget *parent /*= nullptr*/)
    : QDialog(parent), ui(new Ui::ItemFoundDialog)
{
    this->setWindowFlags(Qt::WindowStaysOnTopHint);
    ui->setupUi(this);
    ui->buttonBox->button(QDialogButtonBox::StandardButton::Ok)->setText(tr("Ok"));
    ui->buttonBox->button(QDialogButtonBox::StandardButton::No)->setText(tr("Skip"));
    ui->buttonBox->button(QDialogButtonBox::StandardButton::Abort)->setText(tr("Abort"));

    ui->itemNameShow->setText(item.title);
    ui->shopNameShow->setText(item.shop);
    ui->itemPriceShow->setText(QString::number(item.price, 'f', 2));
    ui->itemIdShow->setText(QString::number(item.id));
    ui->itemLinkShow->setText(QString("<html><head/><body><a href=\"%1\">%1</a></body></html>").arg(item.link));
    this->adjustSize();

    loadImageFromUrlAsync(item.imgsrc, [this](QImage &img)
    {
        QPixmap pixmap = QPixmap::fromImage(img);
        if (pixmap.width() > ui->imageView->width())
            pixmap = pixmap.scaledToWidth(ui->imageView->width(), Qt::TransformationMode::SmoothTransformation);
        ui->imageView->setPixmap(pixmap);
    });
}

ItemFoundDialog::~ItemFoundDialog()
{

}

void ItemFoundDialog::loadImageFromUrlAsync(const QString &url, std::function<void(QImage &img)> onFinished)
{
    manager.get(QNetworkRequest(url));
    QObject::connect(&manager, &QNetworkAccessManager::finished, [=](QNetworkReply *reply)
    {
        onFinished(QImage::fromData(reply->readAll()));
    });
}

QImage ItemFoundDialog::loadImageFromUrl(const QString &url)
{
    volatile bool ok = false;
    QImage image;
    loadImageFromUrlAsync(url, [&](QImage &temp)
    {
        image = temp;
        ok = true;
    });
    while (!ok)
        QCoreApplication::processEvents();
    return image;
}

void ItemFoundDialog::on_buttonBox_clicked(QAbstractButton *button)
{
    this->_result = ui->buttonBox->standardButton(button);
    this->accept();
}
